

package com.hlingsoft.kkh.action;


import com.aliyun.openservices.oss.OSSClient;
import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.aliyun.openservices.oss.model.PutObjectResult;
import com.hlingsoft.kkh.dao.*;
import com.hlingsoft.kkh.entity.*;
import com.hlingsoft.kkh.service.MessageService;
import com.hlingsoft.kkh.util.Common;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 用户
 *
 * @author Herbert
 */
@Controller
@RequestMapping("/user")
public class UserAction extends BaseAction {


    @Autowired
    protected MerchantDao merchantDao;

    @Autowired
    private FocusDao focusDao;

    @Autowired
    private EventsDao eventsDao;

    @Autowired
    private EventCommentsDao eventCommentsDao;

    @Autowired
    private MessageService messageService;

    @Autowired
    private VerifyCodeDao verifyCodeDao;

    private final String defaultHeadImageUrl = "http://kkh.oss-cn-hangzhou.aliyuncs.com/headImg/default.png";

    @Autowired
    private ImageDao imageDao;


    @Autowired
    private LikesDao likesDao;

    @Autowired
    ShareDao shareDao;



    private final int rows=10;

    /**
     * 微信登陆
     *
     * @param name
     * @param gender
     * @param weChatId
     * @param longitude
     * @param latitude
     * @param request
     * @return
     */
    @RequestMapping(value = "/login.json")
    @ResponseBody
    public Map<String, Object> login(
            @RequestParam(value = "name", defaultValue = "0") String name,
            @RequestParam(value = "udId", defaultValue = "0") String udId,
            @RequestParam(value = "headImage", required = false) String headImage,
            @RequestParam(value = "gender", defaultValue = "1") int gender,
            @RequestParam(value = "weChatId", required = false) String weChatId,
            @RequestParam(value = "address", required = false) String address,
            @RequestParam(value = "signature", required = false) String signature,
            @RequestParam(value = "longitude") Double longitude,
            @RequestParam(value = "latitude") Double latitude,
            @RequestParam(value = "phone", required = false) String phone,
            @RequestParam(value = "type", defaultValue = "0") int type,  //0.短信登陆 1.微信登陆 2.微博登陆
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            if (type == 0) {
                AppUser user = userDao.getUserByPhone(phone);
                if (user == null) {
                    user = new AppUser();
                    user.setPhone(phone);
                    user.setWeChatId(weChatId);
                    if (name.equals("0")) {
                        name = phone;
                        String regex = "****";
                        name = name.replaceAll(name.substring(3, 7), regex);
                    }
                    name = Common.encodeStr(name);
                    user.setName(name);
                    user.setUdId(udId);
                    user.setHeadImage(defaultHeadImageUrl);
                    user.setGender(gender);
                    user.setAddress(address);
                    user.setSignature(signature);
                    user.setLatitude(latitude);
                    user.setLongitude(longitude);
                    user.setCreateTime(new Date());
                    user.setUpdateTime(new Date());
                    user.setType(type);
                    userDao.addUser(user);
                } else {
                    user.setUdId(udId);
                    user.setLatitude(latitude);
                    user.setLongitude(longitude);
                    user.setUpdateTime(new Date());
                    userDao.updateUser(user);
                }
                resultMap.put("user", user);
            } else {
                AppUser user = userDao.getUserByWeChatId(weChatId);
                if (user == null) {
                    user = new AppUser();
                    user.setUdId(udId);
                    user.setPhone(phone);
                    user.setWeChatId(weChatId);
                    user.setName(name);

                    //微信头像传到开开会
                    URL url = new URL(headImage);
                    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setConnectTimeout(5 * 1000);
                    InputStream inStream = conn.getInputStream();
                    byte[] data = Common.readInputStream(inStream);
                    SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
                    String dateString = simpleFormat.format(new Date());
                    File imageFile = new File(System.currentTimeMillis()+"");
                    FileOutputStream outStream = new FileOutputStream(imageFile);
                    outStream.write(data);
                    outStream.close();

                    InputStream content = new FileInputStream(imageFile);
                    String fileName = imageFile.getName();
                    putObject(dateString,fileName, content,imageFile.length());
                    headImage = "http://kkh.oss-cn-hangzhou.aliyuncs.com/headImg/" + dateString + "/" + fileName;

                    user.setHeadImage(headImage);
                    user.setGender(gender);
                    user.setAddress(address);
                    user.setSignature(signature);
                    user.setLatitude(latitude);
                    user.setLongitude(longitude);
                    user.setCreateTime(new Date());
                    user.setUpdateTime(new Date());
                    user.setType(type);
                    userDao.addUser(user);
                } else {
                    user.setUdId(udId);
                    user.setLatitude(latitude);
                    user.setLongitude(longitude);
                    user.setUpdateTime(new Date());
                    userDao.updateUser(user);
                }
                resultMap.put("user", user);
            }

            resultMap.put("result", true);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }

        return resultMap;

    }


    /**
     * 个人详情
     *
     * @param userId
     * @param request
     * @return
     */
    @RequestMapping("/detail.json")
    @ResponseBody
    public Map<String, Object> detail(
            @RequestParam(value = "userId") long userId,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            AppUser user = userDao.getUserById(userId);
            long attentionsCount = focusDao.getAttentionsByIdCount(userId);
            user.setAttentionsCount(attentionsCount);
            long fansCount = focusDao.getFansByIdCount(userId);
            user.setFansCount(fansCount);
            long imageCount = 0;
            long eventsCount = eventsDao.getEventsByAppUserIdCount(userId);

            //用户eventComments
            List<EventComments> eventCommentsList = eventCommentsDao.getCommentsListByAppUserId(userId);
            for (EventComments eventComments : eventCommentsList) {
//                String images = eventComments.getImage();
//                imageCount += Common.getParts(images);
                imageCount += imageDao.getImageByEventCommentsIdCount(eventComments.getId());
            }

            user.setEventsCount(eventsCount);
            user.setImagesCount(imageCount);

            resultMap.put("user", user);
            resultMap.put("result", true);

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * 用户编辑
     *
     * @param userId
     * @param name
     * @param gender
     * @param address
     * @param signature
     * @param request
     * @return
     */
    @RequestMapping(value = "/edit.json", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> edit(
            @RequestParam(value = "userId") long userId,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "gender", defaultValue = "-1", required = false) long gender,
            @RequestParam(value = "address", required = false) String address,
            @RequestParam(value = "signature", required = false) String signature,
//            @RequestParam(value = "files", required = false) MultipartFile files,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            AppUser user = userDao.getUserById(userId);
            MultipartFile files = null;
            if (request instanceof MultipartHttpServletRequest) {
                files = ((MultipartHttpServletRequest) request).getFile("files");
            }

            //上传头像
            if (files != null) {
                String fileName = files.getOriginalFilename();
                SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd");
                String dateString = simpleFormat.format(new Date());
                putObject(dateString, fileName, files.getInputStream(),
                        files.getSize());
                String headImage = "http://kkh.oss-cn-hangzhou.aliyuncs.com/headImg/" + dateString + "/" + fileName;
                user.setHeadImage(headImage);
            }
            if (name != null) {
                user.setName(name);
            }

            if (gender != -1) {
                user.setGender(gender);
            }

            if (address != null) {
                user.setAddress(address);
            }
            if (signature != null) {
                user.setSignature(signature);
            }
            user.setUpdateTime(new Date());

            userDao.updateUser(user);
            resultMap.put("user", user);
            resultMap.put("result", true);

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * 用户eventsList接口
     *
     * @param myId
     * @param userId
     * @param request
     * @return
     */
    @RequestMapping(value = "/eventList.json", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> userEventList(
            @RequestParam(value = "myId") long myId,
            @RequestParam(value = "userId") long userId,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            AppUser user = userDao.getUserById(userId);
            if (user != null) {
                //关注人数
                long attentionsCount = focusDao.getAttentionsByIdCount(userId);
                user.setAttentionsCount(attentionsCount);


                //粉丝数
                long fansCount = focusDao.getFansByIdCount(userId);
                user.setFansCount(fansCount);

                //活动数
                long imageCount = 0;
                long eventsCount = eventsDao.getEventsByAppUserIdCount(userId);


                List<EventComments> eventCommentsList = eventCommentsDao.getCommentsListByAppUserId(userId);
                if (eventCommentsList.size() > 0) {
                    for (EventComments eventComments : eventCommentsList) {
                        imageCount += imageDao.getImageByEventCommentsIdCount(eventComments.getId());
                    }

                }
                //活动数
                user.setEventsCount(eventsCount);
                //图片数
                user.setImagesCount(imageCount);


                if (focusDao.getFocus(myId, userId) == null) {
                    user.setIsFocus(0);   //未关注
                } else {
                    user.setIsFocus(1);   //我关注了用户
                    if (focusDao.getFocus(user.getId(), myId) != null) {
                        user.setIsFocus(2); //相互关注
                    }
                }

                List<Events> eventsList = eventsDao.getEventsByAppUserId(userId,0,100);
                for (Events events : eventsList) {
                    EventComments firstEventComments = eventCommentsDao.getFirstEventComments(events.getId());
                    List<Image> imageList = imageDao.getImageByEventCommentsId(firstEventComments.getId());
                    events.setImageList(imageList);
                }

                resultMap.put("user", user);
                resultMap.put("eventsList", eventsList);
                resultMap.put("result", true);
            } else {
                resultMap.put("msg", "用户已被禁用");
                resultMap.put("result", false);
            }

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    @RequestMapping(value = "/eventList1.json", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> userEventList1(
            @RequestParam(value = "myId") long myId,
            @RequestParam(value = "userId") long userId,
            @RequestParam(value = "pageNum",required = false) int pageNum,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            AppUser user = userDao.getUserById(userId);
            if (user != null) {
                //关注人数
                long attentionsCount = focusDao.getAttentionsByIdCount(userId);
                user.setAttentionsCount(attentionsCount);


                //粉丝数
                long fansCount = focusDao.getFansByIdCount(userId);
                user.setFansCount(fansCount);

                //活动数
                long imageCount = 0;
                long eventsCount = eventsDao.getEventsByAppUserIdCount(userId);


                List<EventComments> eventCommentsList = eventCommentsDao.getCommentsListByAppUserId(userId);
                if (eventCommentsList.size() > 0) {
                    for (EventComments eventComments : eventCommentsList) {
                        imageCount += imageDao.getImageByEventCommentsIdCount(eventComments.getId());
                    }

                }
                //活动数
                user.setEventsCount(eventsCount);
                //图片数
                user.setImagesCount(imageCount);


                if (focusDao.getFocus(myId, userId) == null) {
                    user.setIsFocus(0);   //未关注
                } else {
                    user.setIsFocus(1);   //我关注了用户
                    if (focusDao.getFocus(user.getId(), myId) != null) {
                        user.setIsFocus(2); //相互关注
                    }
                }

                List<Events> eventsList = eventsDao.getEventsByAppUserId(userId, (pageNum - 1) * rows,rows);
                for (Events events : eventsList) {
                    EventComments firstEventComments = eventCommentsDao.getFirstEventComments(events.getId());
                    List<Image> imageList = imageDao.getImageByEventCommentsId(firstEventComments.getId());
                    events.setImageList(imageList);
                }

                resultMap.put("user", user);
                resultMap.put("eventsList", eventsList);
                resultMap.put("result", true);
            } else {
                resultMap.put("msg", "用户已被禁用");
                resultMap.put("result", false);
            }

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }



    /**
     * 验证码
     *
     * @param phone
     * @param request
     * @return
     */
    @RequestMapping(value = "/verifyCode.json", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> verifyCode(
            @RequestParam(value = "phone") String phone,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            String str = Common.Randoms();
            resultMap.put("result", true);
            try {
                List<String> list = new ArrayList<>();

                VerifyCode verifyCode = verifyCodeDao.getVerifyCodeByPhone(phone);
                Result result = messageService.sendSmsforEvent(phone, str);
                //短信接口请求成功
                if (result.getCode().equals("2")) {
                    //新用户，插入数据表
                    if (verifyCode == null) {
                        VerifyCode verifyCode1 = new VerifyCode();
                        verifyCode1.setPhone(phone);
                        verifyCode1.setCode(str);
                        verifyCode1.setTime(new Date());
                        verifyCodeDao.addVerifyCode(verifyCode1);
                    }
                    //老用户，更新数据表
                    else {
                        verifyCode.setPhone(verifyCode.getPhone());
                        verifyCode.setTime(new Date());
                        verifyCode.setCode(str);
                        verifyCodeDao.updateVerifyCode(verifyCode);
                    }
                    resultMap.put("msg", result.getMsg());
                    resultMap.put("code", result.getCode());
                    resultMap.put("verifyCode", str);

                }
                //手机号码不对
                else if (result.getCode().equals("406")) {
                    resultMap.put("msg", result.getMsg());
                    resultMap.put("code", result.getCode());
                }
                //其他调用短信接口异常
                else {
                    if (verifyCode != null) {
                        resultMap.put("verifyCode", verifyCode.getCode());
                    }
                    resultMap.put("msg", result.getMsg());
                    resultMap.put("code", result.getCode());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("msg", "服务暂不可用");
            resultMap.put("result", false);
        }

        return resultMap;

    }



    /**
     * 图片删除
     *
     * @param imageId
     * @param request
     * @return
     */
    @RequestMapping(value = "/deleteImage.json")
    @ResponseBody
    public Map<String, Object> deleteImage(
            @RequestParam(value = "imageId") long imageId,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {

            Image imageRecord = imageDao.getImageById(imageId);
            long eventsId = imageRecord.getEventsId();
            long eventCommentsId = imageRecord.getEventCommentsId();


            //判断评论中是否只有张图片，只有一张图片，删除评论

            EventComments firstEventComments = eventCommentsDao.getFirstEventComments(imageRecord.getEventsId());  //获取活动的第一个评论
            EventComments eventComments = eventCommentsDao.getCommentsListById(imageRecord.getEventCommentsId()); //获取图片所在评论


            //判断评论中图片只有一张
            if (imageDao.getImageByEventCommentsIdCount(imageRecord.getEventCommentsId()) == 1) {

                //删除图片
                imageRecord.setAvailable(0);
                imageDao.updateImage(imageRecord);

                //删除图片的分享
                List<Share> shareList = shareDao.getShareByImageId(imageId);
                for (Share share : shareList) {
                    share.setAvailable(0);
                    shareDao.updateShare(share);
                }

                //图片为活动中唯一图片
                if (firstEventComments.getId() == eventComments.getId()) {
                    //删除events
                    Events events = eventsDao.getEventsById(eventsId);
                    events.setAvailable(0);
                    eventsDao.updateEvents(events);

                    //删除评论
                    eventComments.setAvailable(0);
                    eventCommentsDao.updateEventComments(eventComments);

                    //删除点赞
                    List<Likes> likesList = likesDao.getLikesByEventsId(eventsId,0,100);
                    for (Likes likes : likesList) {
                        likes.setAvailable(0);
                        likesDao.updateLikes(likes);
                    }

                    //删除分享
                    List<Share> eventShareList = shareDao.getShareByEventsId(eventsId);
                    for (Share share : eventShareList) {
                        share.setAvailable(0);
                        shareDao.updateShare(share);
                    }
                } else {

                    //删除评论
                    eventComments.setAvailable(0);
                    eventCommentsDao.updateEventComments(eventComments);

                    //删除评论点赞
                    List<Likes> likesList = likesDao.getLikesByEventCommentsId(eventCommentsId,0,100);
                    for (Likes likes : likesList) {
                        likes.setAvailable(0);
                        likesDao.updateLikes(likes);
                    }
                }
            } else {
                imageRecord.setAvailable(0);
                imageDao.updateImage(imageRecord);

                //删除图片的分享
                List<Share> shareList = shareDao.getShareByImageId(imageId);
                for (Share share : shareList) {
                    share.setAvailable(0);
                    shareDao.updateShare(share);
                }
            }
            resultMap.put("result", true);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * 删除events
     *
     * @param eventsId
     * @param request
     * @return
     */
    @RequestMapping(value = "/deleteEvents.json")
    @ResponseBody
    public Map<String, Object> deleteEvents(
            @RequestParam(value = "userId") long userId,
            @RequestParam(value = "eventsId") long eventsId,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            //获取到这个events
            Events events = eventsDao.getEventsById(eventsId);

            if (userId == events.getAppUserId()) {
                //更新events的记录
                events.setAvailable(0);
                eventsDao.updateEvents(events);

                //删除评论
                List<EventComments> eventCommentsList = eventCommentsDao.getCommentsListByEventId(eventsId);
                for (EventComments eventComments : eventCommentsList) {
                    eventComments.setAvailable(0);
                    eventCommentsDao.updateEventComments(eventComments);
                }

                //删除点赞
                List<Likes> likesList = likesDao.getLikesByEventsId(eventsId,0,100);
                for (Likes likes : likesList) {
                    likes.setAvailable(0);
                    likesDao.updateLikes(likes);
                }

                //删除分享
                List<Share> shareList = shareDao.getShareByEventsId(eventsId);
                for (Share share : shareList) {
                    share.setAvailable(0);
                    shareDao.updateShare(share);
                }


                //删除图片
                List<Image> imageList = imageDao.getImageByEventsId(eventsId);
                for (Image image : imageList) {
                    image.setAvailable(0);
                    imageDao.updateImage(image);
                }
                resultMap.put("result", true);
            } else {
                resultMap.put("msg", "只有活动创建者才能删除该活动");
                resultMap.put("result", false);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * 用户搜索
     *
     * @param name
     * @param request
     * @return
     */
    @RequestMapping("/search.json")
    @ResponseBody
    public Map<String, Object> search(
            @RequestParam(value = "name", required = false) String name,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            List<AppUser> userList = new ArrayList<AppUser>();

            if (name == null || (name.replaceAll(" ", "").equals(""))) {

                resultMap.put("userList", userList);
            } else {
                if (Common.isWindows()) {
                    name = Common.encodeStr(name);
                }
                userList = userDao.getUserByName(name);
                resultMap.put("userList", userList);
            }
            resultMap.put("result", true);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }


    /**
     * 退出登录
     * @param userId
     * @param request
     * @return
     */
    @RequestMapping("/logout.json")
    @ResponseBody
    public Map<String, Object> logout(
            @RequestParam(value = "userId") long userId,
            HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            userDao.updateUdIdById(userId);
            resultMap.put("result", true);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("result", false);
        }
        return resultMap;
    }





    public void putObject(String date, String filename, InputStream content,
                          Long size) throws FileNotFoundException {

        // 初始化OSSClient
        OSSClient client = new OSSClient("W6PVM427mSEWlvEz",
                "h7NoXlxcjCqyeOWeuT43LungGmGRSd");



        // 获取指定文件的输入流
        // File file = new File(filePath);
        // InputStream content = new FileInputStream(file);

        // 创建上传Object的Metadata
        ObjectMetadata meta = new ObjectMetadata();

        // 必须设置ContentLength
        meta.setContentLength(size);

        // 上传Object.
        PutObjectResult result = client.putObject("kkh", "headImg/" + date
                + "/" + filename, content, meta);

        // 打印ETag
        System.out.println(result.getETag());
    }


}
